<!--
 * @Author: kongaobo tkfor@foxmail.com
 * @Date: 2024-02-22 09:43:30
 * @LastEditors: huyuhang
 * @LastEditTime: 2024-04-17 15:19:59
 * @FilePath: \asset-management-local\src\views\asset\assetDiscovery\taskManage\add\uploadFile.vue
 * @Description: 上传侧拉
-->
<template>
  <div class="drawerWrap upload-file-drawer">
    <div>
      <el-form
        @submit.prevent
        scroll-to-error
        label-width="180px"
        :model="formData.data"
        ref="formRef"
        :rules="rules"
      >
        <el-form-item class="col-item" label="上传文件" prop="filePath">
          <el-upload
            class="w-90%"
            drag
            multiple
            v-model:file-list="formData.data.filePath"
            :action="actionUrl"
            :headers="uploadHeaders"
            :on-success="uploadSuccess"
            :on-error="uploadError"
          >
            <el-icon class="el-icon--upload"><UploadFilled /></el-icon>
            <div class="el-upload__text"> 将文件拖至此处，或<em>点击上传</em> </div>
            <template #tip>
              <Icon icon="svg-icon:tips" />
              <span style="color: #cccccc"> 仅允许上传单个、批量文件或压缩包 </span>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
    </div>
    <div>
      <el-button type="primary" @click="submit">确 定</el-button>
      <el-button @click="cancel">取 消</el-button>
    </div>
  </div>
</template>
<script lang="ts" setup>
import { UploadFilled } from '@element-plus/icons-vue'
import { getSimpleDeptList } from '@/api/system/dept'
import * as api from '@/api/asset/taskManage'
import { handleTree } from '@/utils/tree'
import { getAccessToken, getTenantId } from '@/utils/auth'

import { assetListType, responseType } from './addFlieInterface'
import { getCurrentInstance, onMounted, reactive, ref } from 'vue'
const emit = defineEmits(['update:model-value', 'submit'])
const { proxy } = getCurrentInstance() as any
const formRef = ref()
const props = defineProps(['params', 'closeOutDrawer'])

const actionUrl: string = import.meta.env.VITE_UPLOAD_URL
const uploadHeaders = ref({
  Authorization: 'Bearer ' + getAccessToken(),
  'tenant-id': getTenantId()
})

const fileList = ref<responseType[]>([])
// 上传成功提示
const uploadSuccess = (res: any): void => {
  let { data } = res
  if (data != null) {
    fileList.value.push(data)
    proxy.$message.success('上传成功')
  } else {
    proxy.$message.error(res.message || '上传失败')
  }
  formData.data.filePath = formData.data.filePath.filter((item) => {
    return item.response.code == 200
  })
  formRef.value.validate()
  // formData.data.filePath.push(data)
}
//上传失败提示
const uploadError = (res: any): void => {
  proxy.$message.error(res.message)
}
const deptList = ref<Tree[]>([]) // 树形结构

const formData = reactive({
  data: {
    dept: [],
    filePath: []
  },
  systemList: [],
  systemCascaderProps: {
    checkStrictly: true,
    label: 'value',
    value: 'id',
    children: 'children',
    emitPath: false
  },
  cascaderProps: {
    checkStrictly: true,
    label: 'name',
    value: 'id',
    children: 'children',
    emitPath: false
  }
})

const fileListValidator = (rule: any, value: any, callback: any) => {
  if (formData.data.filePath.length === 0) {
    callback(new Error('请上传文件'))
  } else {
    callback()
  }
}
const rules = computed(() => ({
  filePath: [{ required: true, validator: fileListValidator, trigger: 'blur' }]
}))
function submit() {
  formRef.value.validate((valid) => {
    if (valid) {
      let temp: Array<assetListType> = fileList.value.map((item): assetListType => {
        const arr: string[] = item.name.split('.')
        const type: string = arr[arr.length - 1]
        return {
          fileName: item.name,
          id: item.id,
          taskId: item.configId,
          fileId: item.configId,
          fileSize: item.size,
          fileType: type,
          filePath: item.path
        }
      })
      handleSubmit(temp)
      console.log(`temp -->`, temp)
    }
  })
}
function handleSubmit(temp?: assetListType[] | null | undefined) {
  props.params?.callBack(temp)
  cancel()
}
function cancel() {
  props.closeOutDrawer()
}
async function getSystemList() {
  const data = await api.getSimpleSystemList()
  formData.systemList = handleTree(data, 'id', 'pid')
}
async function getDeptList() {
  const data = await getSimpleDeptList()
  deptList.value = data
}
onMounted(() => {
  getDeptList()
  getSystemList()
})
</script>
<style lang="scss">
.upload-file-drawer {
  &.el-drawer .el-drawer__body {
    padding: 20px !important;
  }
  .el-cascader {
    width: 90%;
  }
  .dialog-footer {
    display: flex;
    justify-content: center;
  }
}
</style>
